package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.HttpClientUtil;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.mq.mqconst.MqDeadLetterConst;
import com.atguigu.gmall.mq.mqconst.Mqconst;
import com.atguigu.gmall.mq.service.RabbitService;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class ApiOrderController {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitService rabbitService;

    @Value("${ware.url}")
    private String wareUrl;


    @GetMapping("/auth/get/order/by/out/no/{outTradeNo}")
    public Result<OrderInfo> getOrderInfoByOutTradeNo(@PathVariable("outTradeNo") String outTradeNo) {
        OrderInfo orderInfo = orderService.getOrderInfoByOutTradeNo(outTradeNo);
        return Result.ok(orderInfo);
    }

    @GetMapping("/auth/trade")
    public Result<Map<String, Object>> trade(HttpServletRequest request) {
        String userId = request.getHeader("userId");
        if (StringUtils.isEmpty(userId)) {
            return Result.<Map<String, Object>>fail().message("没有获取到有效的userId");
        }
        Map<String, Object> resultMap = orderService.trade(userId);
        return Result.ok(resultMap);
    }

    /**
     * 页面提交订单按钮
     *
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result<Long> submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String userId = request.getHeader("userId");
        if (StringUtils.isEmpty(userId)) {
            return Result.<Long>fail().message("没有找到userId");
        }

        if (CollectionUtils.isEmpty(orderInfo.getOrderDetailList())) {
            return Result.<Long>fail().message("你的商品不能是空的");
        }

        //检查价格是否正确
/*        boolean flag = false;
        List<String> skuNameList = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId()).getData();
            if (!orderDetail.getOrderPrice().equals(skuPrice)) {
                skuNameList.add(orderDetail.getSkuName());
                flag = true;
                break;
            }
        }
        if (flag) {
            return Result.<Long>fail().message("价格已发生变化，请重新加入购物车" + skuNameList);
        }*/

        //检查库存
//        List<OrderDetail> orderDetailListWare = orderInfo.getOrderDetailList();
//        for (OrderDetail orderDetail : orderDetailListWare) {
//            String path = wareUrl + "/hasStock?skuId=" + orderDetail.getSkuId() + "&num=" + orderDetail.getSkuName();
//            String wareNum = HttpClientUtil.doGet(path);
//            if ("0".equals(wareNum)) {
//                return Result.<Long>fail().message("库存不足，请重新购买" + orderDetail.getSkuName());
//            }
//        }

        Long orderId = orderService.saveOrder(orderInfo, userId);

        rabbitService.sendMessage(MqDeadLetterConst.EXCHANGE_NORMAL, MqDeadLetterConst.ROUTING_KEY_DEAD, orderInfo.getId(), message -> {
            message.getMessageProperties().setExpiration(MqDeadLetterConst.EXPIRE_TIME_TEST);
            return message;
        });

        return Result.ok(orderId);
    }

    @GetMapping("/auth/getPayOrderInfo/{orderId}")
    public Result<Map<String, Object>> getPayOrderInfo(@PathVariable("orderId") Long orderId) {
        OrderInfo orderInfo = orderService.getOrderById(orderId);
        String outTradeNo = orderInfo.getOutTradeNo();
        BigDecimal totalAmount = orderInfo.getTotalAmount();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("id", outTradeNo);
        resultMap.put("totalAmount", totalAmount);
        return Result.ok(resultMap);
    }

    //库存系统请求  拆单
/*    @PostMapping("/orderSplit")
    public List<JSONObject> orderSplit(@RequestParam("orderId") Long orderId,
                                       @RequestParam("wareSkuMap") String wareSkuString) {
        //todo 拆单
        OrderInfo orderInfo = orderService.getOrderById(orderId);
        List<Map<String, JSONArray>> wareSkuMapList = JSONObject.parseObject(wareSkuString, List.class);
        wareSkuMapList.stream()
                .map(wareSkuMap->{
                    Set<Map.Entry<String, JSONArray>> entries = wareSkuMap.entrySet();
                    for (Map.Entry<String, JSONArray> entry : entries) {
                        String wareId = entry.getKey();
                        JSONArray skuIdJsonArray = entry.getValue();

                        OrderInfo subOrderInfo = new OrderInfo();
                        BeanUtils.copyProperties(orderInfo, subOrderInfo);
                        subOrderInfo.setId(null);
                        subOrderInfo.setParentOrderId(orderId);

                        List<OrderDetail> collect = orderInfo.getOrderDetailList().stream()
                                .filter(orderDetail -> skuIdJsonArray.contains(orderDetail))
                                .collect(Collectors.toList());

                        subOrderInfo.setOrderDetailList(collect);
                    }
                    return null;
                })

    }*/
}
